package SmartFleet.station;

import java.util.Timer;
import java.util.TimerTask;

import linker.ClientLinker;
import linker.ServerLinker;
import linker.exception.CanNotReadObjectException;
import linker.exception.ErrorCreatingClientSocketException;
import linker.exception.ErrorCreatingServerSocketException;
import smartfleet.communication.carrwprotocol.CarInfo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class AddCarService extends Service {
	
	private static SmartFleetStation	MAIN_ACTIVITY;
	
	private Timer						timer	= new Timer();
	
	private void startservice() {

		this.timer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {

				try {
					ServerLinker server = new ServerLinker(MAIN_ACTIVITY.getMyStation().getPort());
					
					ClientLinker client = server.acceptNewClient();
					
					CarInfo car = (CarInfo) client.readObject();
					MAIN_ACTIVITY.getMyStation().getMyCars().put(car.getId(), car);
					Log.d("ADDCARSERVICE", "CAR: " + car.getId() + " was added!!!");
					
				} catch (CanNotReadObjectException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ErrorCreatingServerSocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ErrorCreatingClientSocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}, 0, 1000);
		
		;
	}
	
	private void stopservice() {

		if (this.timer != null)
			this.timer.cancel();
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}
	
	@Override
	public void onCreate() {

		super.onCreate();
		startservice();
	}
	
	@Override
	public void onDestroy() {

		super.onDestroy();
		stopservice();
	}
	
	public static void setMainActivity(SmartFleetStation activity) {

		MAIN_ACTIVITY = activity;
	}
}
